<template>
	<view>
		<view class="page-body" id="page-body-content">
			<view class="" style="text-align: center;color: #888;line-height: 50px;" v-if="!oldloading && hasOldMsg">
				获取历史数据
			</view>
			<block v-for="(item,index) in messageList" :key="index">
				<!-- 左边消息 -->
				<!-- v-if="item.sender == user.uid" -->
				<view class="" :id="'chatId-'+item.id" @click="tapItem(item,index)">
					<!-- index>=showPage.topIndex -->
					<!-- {{index+""+index< (index*showPage.num>0?index*showPage.num:showPage.num)}} -->
					<!-- 右边消息 -->
					<view v-if="item.sender == userInfo.id" class="chat-item chat-item-right" @touchstart="onPreview">
						<view class="" @click="onUser(item)">
							<!-- <image :size="45" class="avatar" :src="userInfo.avatar"></image> -->
						</view>
						<view class="" style="width: 100%;display: flex;flex-direction: column;justify-content: center;align-items: center;">
							<view @click="onUser(item)" class="" style="display: flex;width: 100%;justify-content: flex-end;">
								<view class="nickname" style="width: auto;display: flex;justify-content: flex-end;">
									{{userInfo.nickname}}
								</view>
							</view>
							<view style="display: flex;width:600rpx ;justify-content: flex-end;">
								<view class="" style="flex: 1;">
								</view>
								<view class="conent-right" style="max-width: 100%;display: flex;justify-content: flex-end;word-break:break-all;">
									<view>
										<view v-if="item.content">
											{{item.content}}
										</view>
										<view v-if="item.extra">

											<view class="" v-if="item.extra.image">
												<image width="100px" height="100px" :src="item.extra.image"></image>
											</view>
											<view v-if="item.extra.type=='goodsDetail'"><text color="#2979ff" :label="item.extra.title||'商品'" size="40" name="bag"></text></view>
										</view>
									</view>
								</view>
							</view>
							<!-- 						<view class="sendTime" style="display: flex;width:600rpx ;justify-content: flex-end;">
								{{item.time}}
							</view> -->
						</view>
					</view>
					<view v-else class="chat-item chat-item-left" @touchstart="onPreview">
						<!-- <view v-if="index%2==0" class="chat-item chat-item-left" @touchstart="onPreview"> -->
						<view class="" @click="onUser(item)">
							<image :size="45" :src="user.avatar||item.avatar" class="avatar"></image>
						</view>
						<view class="" style="width: 100%;">
							<view class="nickname" @click="onUser(item)">{{user.nickname||item.nickname}}</view>
							<view style="max-width:600rpx ;display: flex;">
								<view class="conent-left" style="max-width: 100%;word-break:break-all;">
									<view>
										<view v-if="item.content">
											{{item.content}}
										</view>
										<view v-if="item.extra">
											<view class="" v-if="item.extra.image">
												<image width="100px" height="100px" :src="item.extra.image"></image>
											</view>
											<view v-if="item.extra.type=='goodsDetail'"><text color="#2979ff" :label="item.extra.title||'商品'" size="40" name="bag"></text></view>
										</view>
									</view>
								</view>
								<view class="" style="flex: 1;">
								</view>
							</view>
						</view>
					</view>
					<view class="sendTime" v-if="item.time" style="text-align: center;">
						{{item.time}}
					</view>
				</view>
			</block>
			<!-- 发送消息栏 -->
			<view style="height: 130rpx;"></view>
			<view v-if="info.show &&  (info.title || info.image)" style="padding: 5px 10px;position: fixed;bottom: 70px;right: 10px;display: flex;justify-content: end;">
				<view style="padding: 5px 10px;background-color: aliceblue;border-radius: 15px;" @click="tapInfo(1)">
					<view v-if="info.image">
						<image style="width: 50px;height: 50px;" @error="info.image=''" :src="info.image"></image>
					</view>
					<view v-if="info.title" style="text-align: center;">
						{{info.title}}
					</view>
				</view>
				<view class="" @click="tapInfo(2)" style="border-radius: 50%;background-color: rgba(255, 0, 0, 0.5);height: 20px; line-height: 20px;width: 20px;text-align: center;">
					X
				</view>
			</view>
			<!--  -->
			<view v-if="showTags" style="padding: 5px 10px;position: fixed;bottom: 70px;right: 5px;left: 5px;">
				<view style="background-color: aliceblue;width: 100%;display: flex;justify-content: end;padding: 5px 10px;box-sizing: border-box;">
					<view style="padding: 5px 10px;background-color: aliceblue;border-radius: 15px;" @click="addImage()">
						图片
					</view>
					<!-- #ifndef H5 -->

					<!-- #endif -->
					<view style="padding: 5px 10px;background-color: aliceblue;border-radius: 15px;" @click="addVideo()">
						视频
					</view>
					<view class="" @click="showTags=!showTags" style="position: absolute;border-radius: 50%;background-color: rgba(255, 0, 0, 0.5);height: 20px; line-height: 20px;width: 20px;text-align: center;right: 0px;top: 0px;">
						X
					</view>
				</view>
			</view>
			<view class="msg-fad" id="bottom">
				<view v-if="hasNewMsg" style="position: absolute;bottom: 60px;right: 10px;">
					<view class="box" style="width: 20px; height: 20px;border-radius: 15px;">
						<text type="error" isDot></text>
					</view>
				</view>
				<view class="" style="flex: 1;position: relative;">
					<input type="text" v-model="mTxt" placeholder="请输入消息" />
					<view class="" @click="showTags=!showTags" :style="showTags?'background-color: rgba(255, 0, 0, 0.1);':'background-color: rgba(255, 0, 0, 0.5);'" style="position: absolute;border-radius: 50%;height: 30px; line-height: 24px;width: 30px;text-align: center;right: 15px;top: 7px;font-weight: 900;font-size: 30px;color: #fff;">
						+
					</view>
				</view>
				<view class="">
					<button @click="sendMessage(mTxt)" type="success" style="height: 100%;width: 100%;display: flex; align-items: center;">发送</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	// import {
	// 	sendToChat,
	// 	updateReadState,
	// 	getChat,
	// 	list,
	// 	oneUser
	// } from "./api/chat"
	import {
		dataFormat
	} from "@/utils/yc/Time.js"
	// import {
	// 	onConnect,
	// 	onbindAccount
	// } from './js/cim.web.sdk.js'

	export default {
		data() {
			return {
				showTags: false,
				info: {
					show: false,
					image: "",
					queryString: '',
					route: '',
					title: "",
					type: ''
				},
				preview: false,
				show: false,
				mode: 'range',
				mTxt: "",
				showPage: {
					topIndex: 0,
					num: 20,
				},
				msgList: [],
				// userInfo: uni.getStorageSync("userInfo"),
				user: {},
				page: 1,
				hasNewMsg: false,
				// 获取历史消息
				oldloading: false,
				hasOldMsg: true,
				buttom: {},
				pageShow: true
			};
		},
		// watch: {
		// 	"$store.state.message": function(msg, old) {
		// 		if (msg.sender == this.user.uid) {
		// 			this.msgList.push(msg.content)
		// 			this.scrollToBottom()
		// 		}
		// 	}
		// },
		computed: {
			messageList() {
				// console.log(this.$store.getters.messages)
				var msgs = this.msgList;
				var last = null
				msgs.filter(e => {
					var time = new Date(e.send_time).valueOf();
					var theTime = dataFormat(parseInt(time / 1000))
					if (!last || last.time && last.time != theTime) {
						e.time = theTime
					}
					last = JSON.parse(JSON.stringify(e))
					last.time = theTime
				})
				return msgs
			},
			token() {
				return this.$store.getters.data.token || null
			},
			userInfo() {
				return this.$store.getters.data.userInfo || {
					nickname: "匿名"
				}
			}
		},

		onHide() {
			this.pageShow = false
		},
		async onLoad(options) {
			this.info = options
			if (this.info.title || this.info.image) {
				this.info.show = true
			}
			this.user = options
			if (this.user.nickname) {
				uni.setNavigationBarTitle({
					title: '正在与【' + this.user.nickname + '】对话'
				})
			}
			var date2 = new Date();
			// this.getMessage({
			// 	uid: this.user.uid,
			// 	ltSendTime: date2
			// 	// sendTime: [date1, date2]
			// })
			await this.getlist()
			// await this.getMessage()
			// this.getNewMsg()
			// 接受到消息触发 
			// window.onMessageReceived = this.onMessageReceived
			// 上线返回内容 可写在App.vue 
			// window.onReplyReceived = this.onReplyReceived
			// 登录鉴权 可写在App.vue 
			// window.onConnectFinished = this.onConnectFinished
			// this.scrollToBottom()
		},
		onPageScroll: function(obj) {
			// console.log(obj.scrollTop);//实时获取到滚动的值 
			if (obj.scrollTop < 50) {
				// console.log(this.msgList[0].sendTime)
				this.getMessage({
					uid: this.user.uid,
					ltSendTime: new Date(this.msgList[0].sendTime)
					// sendTime: [date1, date2]
				})
				console.log("获取历史数据"); //实时获取到滚动的值 
			}
		},
		//滚动到底部触发 未读新消息状态设为no
		onReachBottom: function(e) {
			this.hasNewMsg = false
		},
		methods: {
			addVideo() {
				var that = this
				uni.chooseVideo({
					// mediaType:['image', 'video'],
					sourceType: ['camera', 'album'],
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePath));
						// 图片需要先上传拿到服务器的url然后在发送图片url
						that.sendMessage("", {
							image: res.tempFilePath
						})
					}
				});
			},
			addImage() {
				var that = this
				uni.chooseImage({
					count: 6, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success(res) {
						// 图片需要先上传拿到服务器的url然后在发送图片url
						that.sendMessage("", {
							image: res.tempFilePaths[0]
						})
						console.log(JSON.stringify(res.tempFilePaths));
					}
				});
			},
			imageError(e) {
				// 图片如果加载错误  给赋空值
				this.info.image = ""
				// console.log(e)
				return
			},
			getUserInfo() {

			},
			async getNewMsg() {

				var that = this
				setTimeout(() => {
					that.getNewMsg()
				}, 6000)
				if (this.pageShow == true) {
					that.getlist()
				}
			},
			tapItem(item, idx) {
				if (item.extra) {
					if (item.extra.type == 'goodsDetail' && item.extra.queryString) {
						uni.navigateTo({
							url: "/pages/home/homeGoods/goodsDetail?" + item.extra.queryString
						})
					}
				}
			},
			tapInfo(e) {
				var info = this.info
				info.show = false
				if (e == 2) {
					this.info = {
						...info
					}

				} else {
					delete info.show
					this.sendMessage("", JSON.stringify(info))
				}
			},
			async getMessage(params) {

				if (this.oldloading == false && this.hasOldMsg) {
					this.oldloading = true
					var item = this.msgList[0] || {
						id: ""
					}
					const res = await this.$http.post('/api/kuerp/message/getLishiList', {
						max_id: item.id
					})
					if (res.data.length > 0) {
						var list = res.data
						// 返回数据不足 设置没有历史数据
						if (list.length % 10 != 0) {
							this.hasOldMsg = false
						}
						var num = this.msgList.length
						this.msgList.unshift(...list)
						// 第一次 滚动到底部
						if (num == 0) {
							this.scrollToBottom()
						} else {
							this.scrollToBottom(res.data[res.data.length - 1].id)
						}
						setTimeout(() => {
							this.oldloading = false
						}, 1000)
					}

				}
			},
			onPreview() {
				var that = this;
				this.preview = true
				setTimeout(() => {
					that.preview = false
				}, 20000);
				// console.log(this.preview)
			},
			/**
			 *  跳转页面底部
			 */
			scrollToBottom(id) {
				if (id) {
					let _this = this
					let height = ""
					setTimeout(() => {
						// 滚动条到节点Id的位置
						const query = uni.createSelectorQuery().in(_this);
						query.select('#chatId-' + id).boundingClientRect(data => {
							// console.log("得到布局位置信息" + JSON.stringify(data));
							// console.log("节点离页面顶部的距离为" + data.top);
							uni.pageScrollTo({
								scrollTop: data.top,
								duration: 0
							});
						}).exec();
					}, 50)
				} else if (this.preview == false) {
					// 非正在阅读状态 触发到底部
					setTimeout(() => {
						uni.pageScrollTo({
							scrollTop: 99999,
							duration: 0
						});
					}, 500);
					// this.hasNewMsg=false
				} else {
					// 正在阅读状态 更新有未读新消息
					this.hasNewMsg = true
				}
			},
			onUser(e) {
				console.log(e)
			},
			// getMsg(e) {
			// 	var date1 = new Date(Date.parse(e[0].replace(/-/g, "/")));
			// 	var date2 = new Date(Date.parse(e[e.length - 1].replace(/-/g, "/")));
			// 	this.getMessage({
			// 		uid: this.user.uid,
			// 		sendTime: [date1, date2]
			// 	})
			// 	this.show = false
			// 	// console.log(e);
			// },
			formatter(day) {
				const d = new Date()
				let month = d.getMonth() + 1
				const date = d.getDate()
				if (day.month == month && day.day == date + 3) {
					day.bottomInfo = '...'
					day.dot = true
				}
				return day
			},
			async getlist() {
				const res = await this.$http.post('/api/message/getList', {
					page: this.page,
					uid: this.user.uid
				})
				if (res.code == 1 && res.data && res.data.length) {
					this.msgList.push(...res.data)
					this.scrollToBottom()
				}
				// // console.log('Console')
				// if (!this.$store.getters.onConnectWs) {
				// 	onConnect() // 初始化
				// }
			},
			// // 登录鉴权 可写在App.vue 
			// onConnectFinished() {
			// 	if (this.$store.getters.userInfo.uid && this.$store.getters.token) {
			// 		// 登陆
			// 		onbindAccount(this.$store.getters.userInfo.uid + ":" + this.$store.getters.token)
			// 	} else {
			// 		setTimeout(this.onConnectFinished, 1000)
			// 	}
			// 	// onbindAccount(this.userInfo.uid + ":" + this.token)
			// },
			// // 上线返回值 可写在App.vue 
			// onReplyReceived(reply) { // 上线响应
			// 	console.log(reply)
			// 	if (reply.key === 'client_bind' && reply.code === 200) {
			// 		this.$store.commit("onConnectWs", true)
			// 		console.log('上线响应')
			// 	}
			// },
			// 接收消息
			onMessageReceived(message) { // 收消息
				// console.log(message)
				this.msgList.push(JSON.parse(message.content))
				// console.log(message.sender + ': ' + message.content)
				if (message.action === 'ACTION_999') { // 账号在其他设备登陆
					return false
				} else {
					this.updateChatStatus(message)
				}
				this.scrollToBottom()

			},
			async sendMessage(mTxt = "", extra = "{}", format = "0") {
				// console.log(this.userInfo)
				try {
					if (extra && typeof extra == 'string') {
						extra = JSON.parse(extra)
					}
				} catch (e) {
					//TODO handle the exception
				}
				var msg = {
					type: 10,
					sender: this.userInfo.uid,
					receiver: this.user.uid,
					action: "2",
					title: "chat",
					content: {
						content: mTxt
					},
					format: "0",
					extra: extra
				};
				const res = await this.$http.post('/api/message/send', msg)
				if (res.code == 1) {
					if (res.data === 0) {
						uni.removeTabBarBadge({
							index: 2
						})
					} else {
						// var msg = res.data.content
						this.msgList.push(res.data)
						this.scrollToBottom()
						uni.setTabBarBadge({
							index: 2,
							text: res.data + ''
						})
					}
				}

			},
			// 更新阅读状态
			updateChatStatus(message) {
				updateReadState(message).then(res => {
					console.log(res)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import 'chat.scss';

	.avatar {
		width: 70px;
	}

	.nickname {
		color: #555;
	}

	.sendTime {

		font-size: 0.8em;
		color: #aaa;
	}

	.title {
		// color: $u-primary;
		text-align: center;
		padding: 20rpx 0 0 0;
	}
</style>